<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      title="选择商品"
      width="1120px"
      top="10vh"
      append-to-body
      @close="close"
    >
      <!--      <el-tag>-->
      <!--        <i class="el-icon-warning"/>-->
      <!--        &nbsp;在此选择已经创建的券-->
      <!--      </el-tag>-->

      <div class="content">
        <!--筛选-->
        <el-form ref="filterForm" :model="filterForm" :rules="rules" :inline="true" label-width="100px" size="small">
          <el-form-item label="所属门店：" prop="shopId">
            <el-select
              v-model="filterForm.shopId"
              filterable
              collapse-tags
              placeholder="可通过名称搜索"
              clearable
              style="width:400px;"
            >
              <el-option
                v-for="(item, index) in manageShopList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品条码：" prop="eanCode">
            <el-input
              v-model="filterForm.eanCode"
              placeholder="请输入"
              clearable
              style="width:400px;"
            />
          </el-form-item>
          <el-form-item label="商品名称：" prop="goodsName">
            <el-input
              v-model="filterForm.goodsName"
              placeholder="请输入"
              clearable
              style="width:400px;"
            />
          </el-form-item>

          <div>
            <el-form-item label=" ">
              <el-button type="primary" round @click="submitFilterForm">查 询</el-button>
              <el-button round @click="resetFilterForm">重 置</el-button>
            </el-form-item>
          </div>
        </el-form>

        <!-- 列表 -->
        <div>
          <el-table
            v-loading="loading"
            :data="list"
            border
            stripe
            style="width: 100%"
            size="small"
            element-loading-text="加载中"
            empty-text="暂无数据"
          >
            <el-table-column prop="eanCode" label="商品条码" />
            <el-table-column prop="goodsName" label="商品名称" />
            <el-table-column prop="goodsPrice" label="商品价格/元">
              <template slot-scope="scope">
                {{ scope.row.goodsPrice / 100 }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="录入时间" />
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-checkbox
                  v-model="checkedIds"
                  :disabled="originalCheckedIds.includes(scope.row.eanCode)"
                  :label="scope.row.id"
                  @change="(val)=>checkboxChange(val,scope.row)"
                >
                  {{ checkedIds.includes(scope.row.eanCode) ? '已选' : '选择' }}
                </el-checkbox>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <pagination-direction
          v-if="paginationConfig.total!==0"
          :config="paginationConfig"
          @sizeschange="sizesChange"
          @pagechange="pageChange"
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button :disabled="loading||checkedList.length===0" size="small" round type="primary" @click="submit">
          确定<span>（ 已选 {{ checkedList.length }}  ）</span></el-button>
        <el-button :disabled="loading" size="small" round @click="cancel">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { marketingGoodsList } from '@/api/marketing'
import { mapGetters } from 'vuex'

export default {
  props: {
    hasCheckedIds: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      // 配置
      rules: {
        // 门店
        shopId: [
          {
            required: true,
            message: '请选择门店',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, prev, pager, next, jumper', // 分页类型
        pageSizes: [10], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      resolve: null,
      reject: null,
      // 状态
      dialogVisible: null,
      loading: false, // 表格loading
      // 数据
      originalCheckedIds: [],
      checkedIds: [],
      checkedList: [],
      list: [], // 表格数据
      // 筛选数据
      filterForm: {
        eanCode: null,
        goodsName: null,
        shopId: null
      }
    }
  },
  computed: {
    ...mapGetters(['manageShopList'])
  },
  methods: {
    open() {
      this.originalCheckedIds = this.hasCheckedIds
      this.checkedIds = this.hasCheckedIds
      this.filterForm.shopId = this.manageShopList[0].id
      this.fetchData()
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      Object.assign(this.$data, this.$options.data())
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
     * 获取数据
     */

    // 列表
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.$nextTick(() => {
        this.$refs.filterForm.validate((valid, error) => {
          if (valid) {
            this.loading = true
            const params = Object.assign({}, this.filterForm)
            params.page = page
            params.pageSize = pageSize
            // 清除多余字段
            for (const key in params) {
              if (params[key] === '' || params[key] === 'all') {
                delete params[key]
              }
            }
            marketingGoodsList(params)
              .then((res) => {
                this.list = res.data.list
                this.paginationConfig.total = res.data.total
                this.paginationConfig.page = res.data.pageNum
              })
              .finally(() => {
                this.loading = false
              })
          }
        })
      })
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    // 查询
    submitFilterForm() {
      this.fetchData(1)
    },

    // 重置
    resetFilterForm() {
      this.$refs.filterForm.resetFields()
      this.fetchData(1)
    },

    /**
     * 按钮组
     */

    // 保存
    submit() {
      if (this.checkedList.length) this.resolve && this.resolve(this.checkedList)
      this.hide()
    },

    // 取消
    cancel() {
      this.hide()
    },

    /*
    * 状态栏
    * */
    checkboxChange(val, row) {
      if (val) {
        const params = {
          id: row.eanCode,
          name: row.goodsName
        }
        this.checkedList.push(params)
      } else {
        this.checkedList.splice(this.checkedList.findIndex(item => item.id === row.eanCode), 1)
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.content {
  ::v-deep {
    .el-tabs__header {
      margin-bottom: 10px;
      background-color: #fff;
      border-radius: 0 0 5px 5px;
    }

    .el-tabs__nav-wrap::after {
    }

    .el-tabs__active-bar {
      height: 4px;
    }
  }
}
</style>
